﻿// JScript 文件

        var owner;                    //opensocial.Person
        var viewer;                   //opensocial.Person
        var viewerFriends;            // opensocial.Collection
        var viewerFriendsStarBless;   // 类型：{id: {'starBless': json}}
        var ownerStarBless;          //{'starBless':json}
        
    /* Gadget 执行入口 */
        function init() {
          preload();
          reloadAll();
        };
        gadgets.util.registerOnLoadHandler(init);
        
     /* 发送 Opensocial API 请求 */
        function reloadAll() {
          var req = new opensocial.DataRequest();
          
          req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER), 'v')
          req.add(req.newFetchPersonRequest('OWNER'), 'o');
          req.add(req.newFetchPeopleRequest('OWNER_FRIENDS'), 'vf');
          
          req.add(req.newFetchPersonAppDataRequest('OWNER', 'starFrame_x'), 'sx');
          req.add(req.newFetchPersonAppDataRequest('OWNER', 'starFrame_y'), 'sy');
          
          req.add(req.newFetchPersonAppDataRequest('OWNER', 'starBless'), 'sb');
          req.add(req.newFetchPersonAppDataRequest('OWNER_FRIENDS', 'starBless'), 'vfs');
          
          
          
          req.send(onReloadAll);
        };
        
      /* 处理 Opensocial API 响应 */
        function onReloadAll(dataResponse) {
    
          /* 获取数据 */
          
          viewer = dataResponse.get('v').getData() || {};
          owner = dataResponse.get('o').getData() || {};
          
          viewerFriends = dataResponse.get('vf').getData() || {};
          
          var starFrame_x = dataResponse.get('sx').getData()[owner.getId()] || {};
          var starFrame_y = dataResponse.get('sy').getData()[owner.getId()] || {};
          
          ownerStarBless = dataResponse.get('sb').getData()[owner.getId()] || {};
          viewerFriendsStarBless = dataResponse.get('vfs').getData() || {};
          
         
          
          
          /* 显示数据 */
          showStars_Frame(starFrame_x,starFrame_y);
          if(iusedStars>0)
          {
            showStars_User();
            showOwnerBless();
          }
          else
            alterFrame();
        }
        
        /*显示星星星座*/
        function showStars_Frame(srf_x,srf_y)
        {     
           /* 解析当前数据 */
          var jsonx = srf_x['starFrame_x'];
          var jsony = srf_y['starFrame_y'];
          var jx;
          var jy;
          try  {
            jx = gadgets.json.parse(gadgets.util.unescapeString(jsonx)) || [];
            jy = gadgets.json.parse(gadgets.util.unescapeString(jsony)) || [];
          } catch(e) {
            jx = [];jy=[];
          }
          
          var len = jx.length;
          iusedStars=len;
          for (var i = 0; i < len; ++i) {
            istarFrame_x[i]=jx[i];
            istarFrame_y[i]=jy[i];
          }
          showStars();
        }
        
        /*显示用户已经定义好的星星并获取照片地址*/
        function showStars_User()
        {
          userImg=new Array();
          var str_1="<tr>";
          var str_2="<tr>";

          var count=0;
          var number=0;
          var flag;
          
          /* 遍历每个朋友 */
          var starBless;
          for (var friendId in viewerFriendsStarBless) {
            flag=true;
            var data = viewerFriendsStarBless[friendId];
            var friend = viewerFriends.getById(friendId);
            
            /* 解析数据 */
            var json = data['starBless'];
            starBless = [];
            try  {
              starBless = gadgets.json.parse(gadgets.util.unescapeString(json)) || [];
            } catch(e) {
              starBless = [];
            }
            for(var i=0;i<starBless.length;i++)
            {
                var s=starBless[i].split('|');
                if(s[0]==owner.getId())
                {
                    if(flag)
                    {
                        ++count;
                        str_1=str_1+"<td><img src="+friend.getField(opensocial.Person.Field.THUMBNAIL_URL)+" onclick=locateUerBless("+friendId+"); /></td>";
                        str_2=str_2+"<td>"+friend.getDisplayName()+"</td>";
                        
                        flag=false;
                    }
                    
                    var obj=document.getElementById("star"+s[1]);
                    obj.style.visibility="visible";
                    var str="userStarOnmouseover("+s[1]+")";
                    obj.onmouseover=Function(str);
                    str="userStarOnmouseout("+s[1]+")";
                    obj.onmouseout=Function(str);
                    obj=document.getElementById("info"+s[1]);
                    obj.value=starBless[i];
                    document.getElementById("img"+s[1]).src=img2.src;
                    number++;
                }
            }
          }
          
          /*遍历自己*/
          var jownerStarBless=ownerStarBless['starBless'];
          try  {
              starBless = gadgets.json.parse(gadgets.util.unescapeString(jownerStarBless)) || [];
            } catch(e) {
              starBless = [];
          }
          flag=true;
          for(var i=0;i<starBless.length;i++)
          {
              var s=starBless[i].split('|');
              if(s[0]==owner.getId())
              {
                  if(flag)
                  {
                      ++count;
                      str_1=str_1+"<td><img src="+owner.getField(opensocial.Person.Field.THUMBNAIL_URL)+"  onclick=locateUerBless("+owner.getId()+") /></td>";
                      str_2=str_2+"<td>"+owner.getDisplayName()+"</td>";

                    flag=false;
                  }
                  
                  var obj=document.getElementById("star"+s[1]);
                  obj.style.visibility="visible";
                  var str="userStarOnmouseover("+s[1]+")";
                  obj.onmouseover=Function(str);
                  str="userStarOnmouseout("+s[1]+")";
                  obj.onmouseout=Function(str);
                  obj=document.getElementById("info"+s[1]);
                  obj.name=owner.getId();
                  obj.value=starBless[i];
                  document.getElementById("img"+s[1]).src=img2.src;
                  number++;
              }
          }
          iusedFrameStars=number;
          
         var obj=document.getElementById("showblessUser");
         if(parseInt(obj.style.width)<count*65)
         {
             obj.style.width=count*65+5;
         }
         obj.innerHTML="<table cellspacing=2>"+str_1+"</tr>"+str_2+"</tr>"+"</table>";
        }
        
        /*获取拥有者owner在别处的祝福*/
        function showOwnerBless()
        {
         var jownerStarBless=ownerStarBless['starBless'];
          try  {
              starBless = gadgets.json.parse(gadgets.util.unescapeString(jownerStarBless)) || [];
            } catch(e) {
              starBless = [];
          }
          
          var flag;
          var s;
          var count=0;
          var str_1="<tr>";
          var str_2="<tr>";
          var friend;
          
          if(starBless.length>=1)
          {
            s=starBless[0].split('|');
            flag=s[0];
            ++count;
            if(s[0]!=owner.getId())
                friend = viewerFriends.getById(s[0]);
            else
                friend = owner;
            str_1=str_1+"<td><img src="+friend.getField(opensocial.Person.Field.THUMBNAIL_URL)+" /></td>";
            str_2=str_2+"<td>"+friend.getDisplayName()+"</td>";
          }
          
          for(var i=1;i<starBless.length;i++)
          {
              var s=starBless[i].split('|');
              if(s[0]!=flag)
              {
                  if(s[0]!=owner.getId())
                    friend = viewerFriends.getById(s[0]);
                  else
                    friend = owner;
                str_1=str_1+"<td><img src="+friend.getField(opensocial.Person.Field.THUMBNAIL_URL)+" /></td>";
                str_2=str_2+"<td>"+friend.getDisplayName()+"</td>";
                flag=s[0];
                ++count;
              }
           }
         var obj=document.getElementById("showOwnerBless");
         if(parseInt(obj.style.width)<count*65)
         {
             obj.style.width=count*65+5;
         }
         obj.innerHTML="<table cellspacing=2>"+str_1+"</tr>"+str_2+"</tr>"+"</table>";
        }
        
        
         /* 处理坐标保存事件 */
        function onSave_frame() 
        {
          //保存用户的星座坐标
          var jx=new Array();
          var jy=new Array();
          var starBless;
          for(var i=0; i<iusedStars; i++)
          {
            jx.push(istarFrame_x[i]);
            jy.push(istarFrame_y[i]);
          }
          var json_x = gadgets.json.stringify(jx);
          var json_y = gadgets.json.stringify(jy);
          
          var req = opensocial.newDataRequest();
          req.add(req.newUpdatePersonAppDataRequest('VIEWER', 'starFrame_x', json_x));
          req.add(req.newUpdatePersonAppDataRequest('VIEWER', 'starFrame_y', json_y));
          

              req.send(function(dataResponse) {
                alert("我读了");
                postBlessActivity("修改了自己的星座");
               // reloadAll();
              });
        };
        
        /*修改自己的祝福*/
        function alterSelfBless(text)
        {
            if(icurrStarId==-1)
                return;
            var s=document.getElementById("info"+icurrStarId).value;
            var sp=s.split('|');
            var starBless;
            var json;
            
            alert(text);
            
            //如果查看者是owner
            if(viewer.isOwner())
            {
               json=ownerStarBless['starBless'];
               try  {
                  starBless = gadgets.json.parse(gadgets.util.unescapeString(json)) || [];
                  } catch(e) {
                  starBless = [];
                }
                var j=0;
                text=sp[0]+"|"+sp[1]+"|"+text+"|"+owner.getId();
                alert(starBless);
                while(j<starBless.length && starBless[j]!=s)   ++j;
                starBless[j]=text;
                alert("ddd    "+starBless);
            }
            //查看者不是owner
            else
            {
                var friendId=viewer.getId();
                var data = viewerFriendsStarBless[friendId];                
                json = data['starBless'];
                try  {
                   starBless = gadgets.json.parse(gadgets.util.unescapeString(json)) || [];
                 }catch(e) {
                   starBless = [];
                 }
                var j=0;
                text=sp[0]+"|"+sp[1]+"|"+text+"|"+friendId;
                alert(starBless);
                while(j<starBless.length && starBless[j]!=s)   ++j;
                starBless[j]=text;
                alert("ssss    "+starBless);
            }
            
           json= gadgets.json.stringify(starBless);
           alert(json);
             
            /* 发送更新数据请求 */
           var req = opensocial.newDataRequest();
           req.add(req.newUpdatePersonAppDataRequest('VIEWER', 'starBless', json));           
           req.send(function(dataResponse) {
            alert("我读了");
           //reloadAll();
             postBlessActivity( "在"+owner.getDisplayName()+" 那里修改了自己的星愿" );
           });
            
        }
        
        /*删除自己的祝福*/
        function deleteSelfBless()
        {
           if(icurrStarId==-1)
                return;
            var s=document.getElementById("info"+icurrStarId).value;
            var starBless;
            var json;
            if(viewer.isOwner())
            {
               var json=ownerStarBless['starBless'];
               try  {
                  starBless = gadgets.json.parse(gadgets.util.unescapeString(json)) || [];
                  } catch(e) {
                  starBless = [];
                }
                var j=0;
                alert(starBless);
                while(j<starBless.length && starBless[j]!=s)   ++j;
                while(j<starBless.length-1) starBless[j]=starBless[++j];
                starBless.length--;
                alert("ddd   "+starBless);
            }
            //查看者不是owner
            else
            {
                var friendId=viewer.getId();
                var data = viewerFriendsStarBless[friendId];                
                json = data['starBless'];
                try  {
                   starBless = gadgets.json.parse(gadgets.util.unescapeString(json)) || [];
                 }catch(e) {
                   starBless = [];
                 }
                var j=0;
                while(j<starBless.length && starBless[j]!=s)   ++j;
                while(j<starBless.length-1) starBless[j]=starBless[++j];
                starBless.length--;
            }
             
            /* 发送更新数据请求 */
           var req = opensocial.newDataRequest();
           if(starBless.length>0)
           {
                json= gadgets.json.stringify(starBless);
                req.add(req.newUpdatePersonAppDataRequest('VIEWER', 'starBless', json));
           }
           else
                req.add(req.newRemovePersonAppDataRequest('VIEWER','starBless'));
                 
           req.send(function(dataResponse) {
            alert("我读了");
             postBlessActivity( "在"+owner.getDisplayName()+" 那里删除了自己的一个星愿" );
           });
                
        }
        

        
        /*保存用户的自定义星星信息*/
        function saveUser_star(text)
        {
            var oid=owner.getId();
            text=oid+"|"+(iusedFrameStars+1)+"|"+text;
            var starBless;
            var json;
            if(viewer.isOwner())
            {
                text=text+"|"+oid;
                var jownerStarBless=ownerStarBless['starBless'];
                try  {
                  starBless = gadgets.json.parse(gadgets.util.unescapeString(jownerStarBless)) || [];
              } catch(e) {
                  starBless = [];
              }
            }
          else
          {
            var friendId=viewer.getId();
            var data = viewerFriendsStarBless[friendId];
            var friend = viewerFriends.getById(friendId);
            
            text=text+"|"+friendId;
            json = data['starBless'];
            try  {
               starBless = gadgets.json.parse(gadgets.util.unescapeString(json)) || [];
             }catch(e) {
               starBless = [];
             }
           }
            starBless.push(text);
            json= gadgets.json.stringify(starBless);
            alert(json);
             
            /* 发送更新数据请求 */
           var req = opensocial.newDataRequest();
           req.add(req.newUpdatePersonAppDataRequest('VIEWER', 'starBless', json));
           
           alert(starBless);
           
           req.send(function(dataResponse) {
           
            alert("我读了");
           //reloadAll();
            postBlessActivity( "在"+owner.getDisplayName()+" 那里许下了星愿" );
           });
       
        }
        
        /*发送祝福事件活动*/
        function postBlessActivity(text) 
        {  
            var title = text; 
            var params = {};  
            params[opensocial.Activity.Field.TITLE] = title;  
            var activity = opensocial.newActivity(params);  
            opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH,
            function() {
            /* 更新后刷新所有数据 */        
            reloadAll();});
        }